package com.google.webmusic.util;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
/**
 * @author e523437
 */
public class JsonUtil {

    private static Gson gson = new Gson();

    public static String toJSON(Object obj) {
        return gson.toJson(obj);
    }

    public static String toJson(Object o) {
        return toJSON(o);
    }

    /**
     * Only parse the standard format
     * 
     * @param json
     * @return
     */
    public static Map<String, String> toStringMap(String json) {
        Map<String, String> map = new HashMap<String, String>();
        if (json.equals("{}")) return map;
        JsonElement root = new JsonParser().parse(json);
        if (root.isJsonObject()) {
            JsonObject jsonObject = root.getAsJsonObject();
            for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
                if (entry.getValue().isJsonPrimitive()) {
                    map.put(entry.getKey(), entry.getValue().getAsString());
                }
            }
        }
        return map;
    }

    public static <T> T toBean(String json, Class<T> c) {
        return gson.fromJson(json, c);
    }

    public static void main(String args[]) {
        String test = "{  \"w2_expires_in\": 1800,  \"taobao_user_id\": \"3592950886\",  \"taobao_user_nick\": \"sandbox_xw80329\",  \"w1_expires_in\": 12960000,  \"re_expires_in\": 15552000,  \"r2_expires_in\": 259200}";
        System.out.println(toStringMap(test));
    }

	public static <T> List<T> toList(String str, Class<T> cla) {
		Type listType = new TypeToken<List<T>>() {}.getType();
		return gson.fromJson(str, listType);
	}
}
